<?php
class Lib_MediationApi_Signs{
    public static function sort_assoc($data) {
        $new = array();
        foreach($data as $key=>$val){
            $key = strtolower($key);
            $new[$key] = $val;
        }
        ksort($new);
        return $new;
    }

    public static function build_data($data){
        $data = self::sort_assoc($data);
        $data_str = '';
        foreach($data as $key=>$val){
            $data_str .= $key.'='.$val;
        }
        return $data_str;
    }

    public static function sign($data)
    {
        $data = self::build_data($data);
        $sign = self::sm3sign($data);
        return $sign;
    }

    public static function verify($data, $sign_p){
        unset($data['sign']);
        $data = self::build_data($data);
        $sign_c = self::sm3sign($data);
        return $sign_c == $sign_p;
    }
    public static function getNonce()
    {
        $nonce = '';
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        for ($i = 0; $i < 12; $i++) {
            $nonce .= substr($str, rand(0, 61), 1);
        }
        return $nonce;
    }
    public static function sm3sign($str){
        $sm3obj = new Lib_MediationApi_SM3();
        return $sm3obj -> sign($str);
    }
}